package com.xmall.product.controller;

import com.xmall.annotation.LoginRequiredFalse;
import com.xmall.aspect.OperateRecord;
import com.xmall.aspect.RepeatSubmit;
import com.xmall.define.base.Result;
import com.xmall.define.dict.OperateTypeEnum;
import com.xmall.validate.group.AddGroup;
import com.xmall.validate.group.UpdateGroup;
import com.xmall.product.define.dto.category.CategoryDto;
import com.xmall.product.define.dto.category.CategoryTreeDto;
import com.xmall.product.service.ICategoryService;
import com.xmall.product.define.request.category.CategoryUpdateRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 商品分类
 */
@RestController
@RequestMapping("/service/product/category")
public class CategoryController {

    @Resource
    private ICategoryService categoryService;

    /**
     * 分类树
     */
    @LoginRequiredFalse
    @GetMapping("/treeList")
    public Result<List<CategoryTreeDto>> treeList(){
        List<CategoryTreeDto> permissionList = categoryService.treeList();
        return Result.success(permissionList);
    }

    /**
     * 子分类列表
     */
    @GetMapping("/children/{parentId}")
    public Result<List<CategoryDto>> children(@PathVariable("parentId") Long parentId){
        List<CategoryDto> list = categoryService.children(parentId);
        return Result.success(list);
    }

    /**
     * 详情
     */
    @GetMapping("/{id}")
    public Result<CategoryDto> info(@PathVariable("id") Long id){
        CategoryDto categoryDto = categoryService.info(id);
        return null != categoryDto ? Result.success(categoryDto) : Result.error();
    }

    /**
     * 新增
     */
    @OperateRecord(type = OperateTypeEnum.ADD)
    @RepeatSubmit
    @PreAuthorize("hasAuthority('product:category:save')")
    @PostMapping("/save")
    public Result save(@Validated(value = AddGroup.class) @RequestBody CategoryUpdateRequest request){
        categoryService.saveEntity(request);
        return Result.success();
    }

    /**
     * 编辑
     */
    @OperateRecord(type = OperateTypeEnum.UPDATE)
    @PreAuthorize("hasAuthority('product:category:update')")
    @PostMapping("/update")
    public Result update(@Validated(value = UpdateGroup.class) @RequestBody CategoryUpdateRequest request){
        categoryService.updateEntity(request);
        return Result.success();
    }

    /**
     * 删除
     */
    @OperateRecord(type = OperateTypeEnum.DELETE)
    @PreAuthorize("hasAuthority('product:category:delete')")
    @PostMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Long id){
        categoryService.deleteEntity(id);
        return Result.success();
    }

}
